package com.uhb.base.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.Properties;

public class ConfigurtionBean {
	private static final Logger logger = LoggerFactory.getLogger(ConfigurtionBean.class);
	private static Properties appProperties = null;
	private static Object ob = new Object();

	public ConfigurtionBean() {
		synchronized (ob) {
			if (appProperties != null) {
				throw new RuntimeException("Can't Create new Configuration Bean");
			}
			appProperties = new Properties();
			InputStreamReader in = null;
			try {
				in = new InputStreamReader(getClass().getResourceAsStream("/api.properties"), "UTF-8");
			} catch (UnsupportedEncodingException e1) {
				logger.error("Can't find app.properties in classpath.");
			}
			try {
				appProperties.load(in);
			} catch (IOException e) {
				logger.error("Can't find app.properties in classpath.");
			}
			if (in != null) {
				try {
					in.close();
				} catch (IOException e) {
					logger.error("Can't close app.properties InputStreamReader");
				}
			}
		}
	}

	public static Properties getConfProperties(){
	    Properties properties = new Properties();
        InputStreamReader in = null;
        try {
            in = new InputStreamReader(ConfigurtionBean.class.getResourceAsStream("/api.properties"), "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            logger.error("Can't find app.properties in classpath.");
        }
        try {
            properties.load(in);
        } catch (IOException e) {
            logger.error("Can't find app.properties in classpath.");
        }
        if (in != null) {
            try {
                in.close();
            } catch (IOException e) {
                logger.error("Can't close app.properties InputStreamReader");
            }
        }
        
	    return properties;
	}
	
	public String get(String key) {
		return appProperties.getProperty(key);
	}
	
	public int getAsInt(String key, String defaultValue) {
        return Integer.parseInt(appProperties.getProperty(key, defaultValue));
    }
	
	public long getAsLong(String key, String defaultValue) {
        return Long.parseLong(appProperties.getProperty(key, defaultValue));
    }
	
	public double getAsDouble(String key) {
        return Double.parseDouble(appProperties.getProperty(key));
    }

	public String get(String key, String defaultValue) {
		return appProperties.getProperty(key, defaultValue);
	}
}
